package com.example.handpose_front.VideoPage;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.Range;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.handpose_front.R;
import com.example.handpose_front.utils.OKHttpUtil.HttpUrl;
import com.example.handpose_front.utils.OKHttpUtil.HttpVideo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class VideoActivity extends Activity {

    private static final String TAG = "VideoActivity";
    private static final int REQUEST_PERMISSION_CODE = 1;

    private SurfaceView surfaceView;
    private Button startButton;
    private Button stopButton;
    private Surface surface;

    private CameraDevice cameraDevice; // Declare cameraDevice
    private CameraCaptureSession captureSession; // Declare captureSession

    private MediaRecorder mediaRecorder;
    private boolean isRecording = false;
    private String videoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);  // 使用你自己的布局文件

        surfaceView = findViewById(R.id.surfaceView);  // 使用 SurfaceView
        startButton = findViewById(R.id.start_record_button);
        stopButton = findViewById(R.id.stop_record_button);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_PERMISSION_CODE);
        }
        // 获取视频文件存储路径
        videoPath = new File(getExternalFilesDir(null), "video_record.mp4").getAbsolutePath();
        startButton.setOnClickListener(v -> {
            // 在点击开始录制按钮时请求权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, REQUEST_PERMISSION_CODE);
            } else {
                // 如果权限已经授予，直接开始录制
                startRecording();
            }
        });
        // 设置 SurfaceView 的 Surface
        SurfaceHolder holder = surfaceView.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                surface = holder.getSurface();  // 获取 Surface
                openCamera();  // 打开摄像头
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                // Do nothing for now
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // 释放摄像头资源
                if (cameraDevice != null) {
                    cameraDevice.close();
                }
            }
        });

        startButton.setOnClickListener(v -> startRecording());
        stopButton.setOnClickListener(v -> stopRecording());
    }

    // 打开摄像头
    private void openCamera() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            // 检查摄像头权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "无摄像头权限", Toast.LENGTH_SHORT).show();
                return;
            }

            String cameraId = cameraManager.getCameraIdList()[0]; // 默认后置摄像头
            cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
                @Override
                public void onOpened(@NonNull CameraDevice camera) {
                    cameraDevice = camera;
                    createCameraPreviewSession(); // 启动预览
                }

                @Override
                public void onDisconnected(@NonNull CameraDevice camera) {
                    camera.close();
                    cameraDevice = null;
                }

                @Override
                public void onError(@NonNull CameraDevice camera, int error) {
                    camera.close();
                    cameraDevice = null;
                    Log.e(TAG, "摄像头打开失败，错误码: " + error);
                    runOnUiThread(() ->
                            Toast.makeText(VideoActivity.this, "摄像头不可用", Toast.LENGTH_SHORT).show()
                    );
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
            Toast.makeText(this, "无法访问摄像头: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 创建摄像头预览会话
    private void createCameraPreviewSession() {
        if (cameraDevice == null) {
            Log.e(TAG, "CameraDevice is null, cannot create session");
            return;
        }
        try {
            // 1. 获取CameraCharacteristics以查询设备支持的功能
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            String cameraId = cameraManager.getCameraIdList()[0];
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);

            // 2. 获取最佳预览尺寸（基于SurfaceView的尺寸）
            Size optimalSize = getOptimalPreviewSize(characteristics);
            surfaceView.getHolder().setFixedSize(optimalSize.getWidth(), optimalSize.getHeight());
            surface = surfaceView.getHolder().getSurface();

            // 3. 创建预览请求Builder
            CaptureRequest.Builder captureRequestBuilder =
                    cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);

            // 4. 配置自动对焦和曝光设置
            captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);

            // 自动对焦设置（如果设备支持）
            int[] afModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
            if (Arrays.asList(afModes).contains(CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)) {
                captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            }

            // 5. 配置帧率和防抖（如果支持）
            captureRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, new Range<>(30, 30));

            // 6. 配置显示方向
            int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int deviceOrientation = ORIENTATIONS.get(rotation);
            int jpegOrientation = (sensorOrientation + deviceOrientation + 360) % 360;
            captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, jpegOrientation);

            // 7. 创建CaptureSession
            cameraDevice.createCaptureSession(
                    Collections.singletonList(surface),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            if (cameraDevice == null) {
                                return;
                            }

                            captureSession = session;
                            try {
                                // 8. 设置重复请求以保持预览
                                captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                                        CaptureRequest.CONTROL_AE_MODE_ON);

                                CaptureRequest request = captureRequestBuilder.build();
                                captureSession.setRepeatingRequest(request, null, null);
                            } catch (CameraAccessException e) {
                                Log.e(TAG, "Failed to start preview: " + e.getMessage());
                            }
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            Log.e(TAG, "Camera configuration failed");
                            Toast.makeText(VideoActivity.this, "摄像头配置失败", Toast.LENGTH_SHORT).show();
                        }
                    },
                    null
            );

        } catch (CameraAccessException e) {
            Log.e(TAG, "Camera access exception: " + e.getMessage());
        }
    }

    // 辅助方法：获取最佳预览尺寸
    private Size getOptimalPreviewSize(CameraCharacteristics characteristics) {
        StreamConfigurationMap map = characteristics.get(
                CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        Size[] previewSizes = map.getOutputSizes(SurfaceHolder.class);

        // 优先选择1280x720，如果没有则选择第一个可用尺寸
        Size defaultSize = new Size(1280, 720);
        for (Size size : previewSizes) {
            if (size.getWidth() == 1280 && size.getHeight() == 720) {
                return size;
            }
        }
        return previewSizes.length > 0 ? previewSizes[0] : defaultSize;
    }

    // 屏幕方向映射表
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 0);
        ORIENTATIONS.append(Surface.ROTATION_90, 90);
        ORIENTATIONS.append(Surface.ROTATION_180, 180);
        ORIENTATIONS.append(Surface.ROTATION_270, 270);
    }

    // 开始录制视频
    private void startRecording() {
        if (isRecording) {
            Toast.makeText(this, "已经在录制", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cameraDevice == null) {
            Toast.makeText(this, "摄像头未准备好，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            // 1. 先关闭预览会话，避免冲突
            if (captureSession != null) {
                captureSession.close();
                captureSession = null;
            }

            // 2. 配置 MediaRecorder
            mediaRecorder = new MediaRecorder();

            // 视频源（使用 SURFACE 适配 Camera2）
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            // 必须设置视频参数，否则会报错
            mediaRecorder.setVideoEncodingBitRate(10_000_000); // 10 Mbps
            mediaRecorder.setVideoFrameRate(30); // 30 fps
            mediaRecorder.setVideoSize(1280, 720); // 分辨率

            // 设置输出文件路径
            File videoFile = new File(getExternalFilesDir(null), "video_record.mp4");
            videoPath = videoFile.getAbsolutePath();
            mediaRecorder.setOutputFile(videoPath);

            // 3. 准备 MediaRecorder（必须在获取 Surface 之前调用）
            mediaRecorder.prepare();

            // 4. 创建新的录制会话（同时支持预览和录制）
            Surface recorderSurface = mediaRecorder.getSurface();
            List<Surface> surfaces = new ArrayList<>();
            surfaces.add(surface); // 预览 Surface
            surfaces.add(recorderSurface); // 录制 Surface

            CaptureRequest.Builder captureRequestBuilder =
                    cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            captureRequestBuilder.addTarget(surface); // 预览目标
            captureRequestBuilder.addTarget(recorderSurface); // 录制目标

            cameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    captureSession = session;
                    try {
                        mediaRecorder.start();
                        isRecording = true;
                        Toast.makeText(VideoActivity.this, "开始录制", Toast.LENGTH_SHORT).show();

                        // 设置重复请求以保持录制
                        captureSession.setRepeatingRequest(
                                captureRequestBuilder.build(),
                                null,
                                null
                        );
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                        Toast.makeText(VideoActivity.this, "录制失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    Log.e(TAG, "录制会话配置失败");
                    Toast.makeText(VideoActivity.this, "无法启动录制", Toast.LENGTH_SHORT).show();
                }
            }, null);

        } catch (IOException | CameraAccessException e) {
            e.printStackTrace();
            Toast.makeText(this, "录制失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            releaseMediaRecorder();
        }
    }

    // 停止录制视频
    private void stopRecording() {
        try {
            if (captureSession != null) {
                captureSession.close();  // 先关闭当前会话
                captureSession = null;
            }

            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.reset();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } finally {
            releaseMediaRecorder();
            isRecording = false;

            // 延迟恢复预览，确保资源释放完成
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                if (!isRecording && cameraDevice != null) {
                    createCameraPreviewSession();
                }
            }, 300);  // 延迟300ms
        }
        uploadVideo();
    }

    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
    // 上传视频文件
    // 上传视频文件
    private void uploadVideo() {
        File videoFile = new File(videoPath);
        if (!videoFile.exists()) {
            Toast.makeText(this, "视频文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 使用真实的服务器地址（示例，请替换为你的实际地址）
        String baseUrl = HttpUrl.getBaseUrl();

        try {
            // 使用 HttpVideo 类进行文件上传
            String response = HttpVideo.postFileSyncRequest(
                    baseUrl,
                    null,  // 不需要额外参数
                    "video",  // 模块名
                    "upload", // 方法名
                    videoFile
            );

            if (response != null && response.contains("200")) {
                Toast.makeText(this, "视频上传成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "视频上传失败: " + response, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "上传异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，继续操作
                startRecording();
            } else {
                // 权限被拒绝，无法录制视频
                Toast.makeText(this, "权限被拒绝，无法录制视频", Toast.LENGTH_SHORT).show();
            }
        }
    }

}
